﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using c_work.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Work.Models;

namespace Work.Controllers
{
	[Route("[Controller]/[Action]")]
	[ApiController]
	public class CommentsController : Controller
	{
		private readonly DBContext _context;

		public CommentsController(DBContext context)
		{
			_context = context;
		}

		/// <summary>
		/// 获取文章评论
		/// </summary>
		/// <returns></returns>
		[NoSign]
		public async Task<string> Index(int id)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var list = await _context.Comments.ToListAsync();
			var data = list.Where(i => i.BlogId == id);
			dic.Add("data", data);
			dic.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 发表评论
		/// </summary>
		/// <param name="comment"></param>
		/// <returns></returns>
		[HttpPost]
		public string Create(Comment comment)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			Comment i = new Comment()
			{
				BlogId = comment.BlogId,
				Email = comment.Email,
				Content = comment.Content,
				CreateAt = DateTime.Now.ToString("yyyy-MM-dd").ToString()
			};
			try
			{
				_context.Comments.Add(i);
				_context.SaveChanges();
				dic.Add("code", 0);
				dic.Add("msg", "成功");
			}
			catch (Exception e)
			{
				dic.Add("code", 0);
				dic.Add("msg", "失败："+e);
				throw;
			}
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}


		[HttpPost, ActionName("Delete")]
		[ValidateAntiForgeryToken]
		public async Task<IActionResult> DeleteConfirmed(int id)
		{
			var comment = await _context.Comments.FindAsync(id);
			_context.Comments.Remove(comment);
			await _context.SaveChangesAsync();
			return RedirectToAction(nameof(Index));
		}

		private bool CommentExists(int id)
		{
			return _context.Comments.Any(e => e.Id == id);
		}
	}
}
